<template>
	<div v-if="isHaveTitle" class="zs-align-center zs-space-bottom zs-space-top-lg zs-space-bottom-sm" :id="id">
		<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
		<div class="zs-title">{{ title }}</div>
	</div>
	<div class="zs-card zs-space-bottom">
		<el-form :validate-on-rule-change="false" ref="TimeForm" :model="formData.data" :rules="formData.rules" :label-width="labelWidth || '100px'">
			<el-form-item label="生效时间：" prop="effectTime">
				<el-date-picker clearable :disabled="isReadOnly" @visible-change="getEffectState('effect')" v-model="formData.data.effectTime" style="width: 100%" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" value-format="x" />
			</el-form-item>
			<el-form-item label="失效时间：" prop="expireTime">
				<el-date-picker clearable :disabled="isReadOnly" @visible-change="getEffectState('expire')" v-model="formData.data.expireTime" style="width: 100%" type="datetime" placeholder="请选择" format="YYYY-MM-DD HH:mm:ss" value-format="x" />
			</el-form-item>
			<el-form-item label="生效状态：" prop="effectState">
				<el-select disabled v-model="formData.data.effectState" class="zs-full-item" placeholder=" ">
					<el-option v-for="item in dictObj.VALIDATE_FLAG" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
				</el-select>
			</el-form-item>
			<slot :formData="formData.data" />
		</el-form>
	</div>
</template>

<script setup>
	import { reactive, ref } from 'vue';
	import { useStore } from 'vuex';
	let store = useStore();
	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG']);

	const emits = defineEmits(['timeChange']);

	// eslint-disable-next-line no-unused-vars
	let props = defineProps({
		title: { type: String },
		id: { type: String },
		isReadOnly: { type: Boolean },
		labelWidth: { type: String },
		startFiledName: { type: String, default: "startTime" },
		endFiledName: { type: String, default: "endTime" },
		isHaveTitle: { type: Boolean, default: true },
	});

	let TimeForm = ref();
	let formData = reactive({
		data: {
			effectTime: new Date(new Date().toLocaleDateString()).getTime(),
			expireTime: new Date('2100-12-31 23:59:59').getTime(),
			effectState: '1',
		},
		rules: {
			effectTime: [
				{ required: true, message: '请选择生效时间', trigger: ['blur', 'change'] },
				{ validator: endDateValid, trigger: ['blur', 'change'] },
			],
			expireTime: [
				{ required: true, message: '请选择失效时间', trigger: ['blur', 'change'] },
				{ validator: endDateValid, trigger: ['blur', 'change'] },
			],
		},
	});

	// 自动计算获取生效状态
	function getEffectState(type) {
		if (formData.data.effectTime && formData.data.expireTime) {
			let startTime = formData.data.effectTime;
			let endTime = formData.data.expireTime;
			let nowTime = new Date().getTime();
			if (startTime < nowTime && nowTime < endTime) {
				formData.data.effectState = '1';
			} else {
				formData.data.effectState = '0';
			}
		}
		emits('timeChange', type);
	}
	// 失效时间自定义校验
	function endDateValid(rule, value, callback) {
		if (formData.data.expireTime && formData.data.effectTime) {
			if (rule.field === 'effectTime') {
				if (formData.data.expireTime > value) {
					TimeForm.value.clearValidate('expireTime');
					callback();
				} else {
					callback(new Error('生效时间不能大于失效时间'));
				}
			} else {
				if (formData.data.effectTime < value) {
					TimeForm.value.clearValidate('effectTime');
					callback();
				} else {
					callback(new Error('失效时间不能小于有效时间'));
				}
			}
		}
	}

	function restTime() {
		formData.data = {};
		TimeForm.value.resetFields();
	}

	function checkRequired() {
		// return TimeForm.value.validate(valid => {
		// 	return valid;
		// });
		return new Promise(resolve => TimeForm.value.validate(resolve))
	}

	function validateForm () {
		let model = getFiled()
		return new Promise((resolve, reject) => {
			TimeForm.value.validate(valid => {
				let result = valid ? model : false;
				resolve(result);
			});
		});
	}

	function getFiled() {
		let model = {}
		model[props.startFiledName] = formData.data.effectTime
		model[props.endFiledName] = formData.data.expireTime
		return model
	}

	function setTime(data) {
		formData.data.effectTime = data.effectTime || ref(new Date(new Date().toLocaleDateString()).getTime());
		formData.data.expireTime = data.expireTime || ref(new Date('2100-12-31 23:59:59').getTime());
		getEffectState();
	}

	defineExpose({ restTime, checkRequired, formData, getEffectState, setTime, getFiled, validateForm });
</script>
